using System;
using System.Windows.Forms;
using System.IO;

namespace PSSymbolStore.Manager.Windows
{
    public partial class ChooseSymbolStore : Form
    {
        public ChooseSymbolStore()
        {
            InitializeComponent();
        }

        public string SymbolStoreLocation { get; set; }

        private void buttonBrowse_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                txtSymbolStore.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            SymbolStoreLocation = txtSymbolStore.Text;
            buttonOK.Enabled = (!String.IsNullOrEmpty(SymbolStoreLocation));
        }

        private static bool IsValidSymbolStore(string location)
        {
            using (new Hourglass())
            {
                return File.Exists(Path.Combine(location, "pingme.txt"))
                    && Directory.Exists(Path.Combine(location, "000Admin"));
            }
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            // Remove any trailing slashes from SymbolStoreLocation
            SymbolStoreLocation = SymbolStoreLocation.TrimEnd('\\');

            if (IsValidSymbolStore(SymbolStoreLocation))
            {
                DialogResult = DialogResult.OK;
            }
            else
            {
                DisplayInvalidSymbolStoreError(SymbolStoreLocation);
            }
        }

        private static void DisplayInvalidSymbolStoreError(string symbolStoreLocation)
        {
            SymbolStoreErrorForm.Show(symbolStoreLocation);
            //MessageBox.Show(String.Format("Symbol store not found at \"{0}\"", symbolStoreLocation), "Not Found",
            //                MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }
    }
}